import ssl
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json


# 从配置文件中读取邮件相关信息
def load_config():
    with open("config.json", "r") as file:
        return json.load(file)


def send_email(subject, body, config):

    from_email = config["from_email"]
    password = config["password"]
    smtp_server = config["smtp_server"]
    smtp_port = config["smtp_port"]
    to_email = config["to_email"]

    # 设置邮件内容
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
            server.login(from_email, password)
            text = msg.as_string()
            server.sendmail(from_email, to_email, text)
            print(f"邮件已发送到 {to_email}")
    except Exception as e:
        print(f"邮件发送失败: {e}")


def complete_notify(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()  # 记录函数开始时间
        result = func(*args, **kwargs)
        end_time = time.time()  # 记录函数结束时间

        # 计算函数执行耗时
        execution_time = end_time - start_time

        # 加载配置
        config = load_config()

        # 发送邮件通知
        subject = f"执行完成！\n"
        body = f"执行耗时: {execution_time:.4f} 秒"
        send_email(subject, body, config)
        return result
    return wrapper

